package fr.cephb.joperon.core.iterator;

import com.sleepycat.db.Cursor;
import com.sleepycat.db.DatabaseEntry;
import com.sleepycat.db.DatabaseException;
import com.sleepycat.db.LockMode;
import com.sleepycat.db.OperationStatus;

/**
 * Iterator iterating between two DatabaseEntry keys
 * When called at first time, the cursor move to the first occurend
 * of the given key invoking <code>getSearchKeyRange</code>
 * @author lindenb
 *
 */
public abstract class KeyRangeIterator
	extends DatabaseEntriesIterator {
	private boolean wasCalledOnce=false;
	
	/**
	 * 
	 * @param cursor the cursor
	 * @param key the key where we should move at the first call
	 */
	public KeyRangeIterator(Cursor cursor,DatabaseEntry key)
		{
		super(cursor,key, new DatabaseEntry());
		}
		
	@Override
	protected OperationStatus moveCursor() throws DatabaseException
		{
		if(!wasCalledOnce)
			{
			wasCalledOnce=true;
			OperationStatus os= this.cursor.getSearchKeyRange(
					_nextValue.first(),
					_nextValue.second(),
					LockMode.DEFAULT
					);
			return os;
			}
		else
			{
			return  super.moveCursor();
			}
		}
	
	@Override
	/** return true if the key of the cursor is <code>isInRange</code> 
	 * 
	 */
	protected boolean validateCursor() throws DatabaseException
		{
		return isInRange(_nextValue.first());
		}
	/** 
	 * return wether the current DatabaseEntry is in a given range
	 * @param entry
	 * @return true if the key is in the range
	 * @throws DatabaseException
	 */
	protected abstract boolean isInRange(DatabaseEntry entry) throws DatabaseException;
	}
